
<template>
  <div class="rq">
    <span @click="open" class="showChapter">章节信息>></span>
    <div class="tou">
      <div class="pal">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ name: 'writer' }"
            >工作台</el-breadcrumb-item
          >
          <el-breadcrumb-item>这是一个测试</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <div class="par">
        <el-button size="small" @click="recoverDelete" v-if="isDeleteItem"
          >恢复</el-button
        >
        <el-button
          size="small"
          @click="saveChapter"
          v-if="currentChapter.chapterOrder <= -1 && !isDeleteItem"
          >保存</el-button
        >
        <el-popconfirm
          title="存稿后的草稿章节将被分配最新的章节序，且将无法删除。"
          @confirm="theSaveAsDraft"
          v-if="currentChapter.chapterOrder == -1 && !isDeleteItem"
          class="tcSave"
        >
          <el-button size="small" slot="reference" type="warning"
            >保存为存稿</el-button
          >
        </el-popconfirm>

        <!-- 关于发布的几个问题 -->
        <!-- 1.发布只能发布存稿，即chapterOder>0 -->
        <!-- 2.发布将chapterOder最小的值章节发布 -->
        <el-button
          type="primary"
          size="small"
          @click="dialogVisible = true"
          v-if="currentChapter.chapterOrder < -1"
          >发布</el-button
        >
        <el-button
          slot="reference"
          type="danger"
          size="small"
          v-if="currentChapter.chapterOrder == -1 && !isDeleteItem"
          @click="deleteTipsTc"
          >删除</el-button
        >
        <el-dialog title="提示" :visible.sync="deleteDialog" width="30%">
          <span>{{ deleteTips }}</span>
          <span slot="footer" class="dialog-footer">
            <el-button @click="deleteDialog = false">取 消</el-button>
            <el-button type="primary" @click="deleteCh">确 定</el-button>
          </span>
        </el-dialog>
        <!-- <el-button size="small" 
          >定时发布</el-button
        > -->
      </div>
      <el-dialog
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
        width="30%"
      >
        <template slot="title">
          <span style="font-size: 18px">发布</span>
          <span style="font-size: 12px; color: #909399">按存稿顺序发布</span>
        </template>
        <el-form ref="form" :model="release">
          <el-form-item label="发布类型">
            <el-radio v-model="release.releaseType" label="1"
              >立刻发布</el-radio
            >
            <el-radio v-model="release.releaseType" label="2"
              >定时发布</el-radio
            >
          </el-form-item>
          <el-form-item label="发布周期" v-if="release.releaseType == 2">
            <el-radio v-model="release.releaseCycle" label="1"
              >仅此一次</el-radio
            >
            <el-radio v-model="release.releaseCycle" label="2">每天</el-radio>
            <!-- <el-radio v-model="release.type" label="3"></el-radio> -->
          </el-form-item>
          <el-form-item label="发布时间" v-if="release.releaseType == 2">
            <!-- <el-date-picker
              v-model="release.time"
              type="time"
              placeholder="选择日期时间"
              format="yyyy-MM-dd HH:mm"
              @change="qdTime"
            ></el-date-picker> -->
            <el-time-picker
              v-model="release.releaseTime"
              value-format="HH:mm"
              format="HH:mm"
              placeholder="任意时间点"
            >
            </el-time-picker>
          </el-form-item>
          <el-form-item label="发布章节数">
            <el-input-number
              size="mini"
              v-model="release.chapterNumber"
            ></el-input-number>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="sendReleaseRequest"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
    <div class="toAction">
      <div style="font-size: 1.2em">
        <!-- <el-button type="text" icon="el-icon-chat-line-square" class="an"
          >作家的话</el-button
        > -->
        <el-button
          type="text"
          icon="el-icon-time"
          class="an"
          @click="selectChapterHistory"
          v-if="!isDeleteItem"
          >历史版本</el-button
        >
        <!-- <el-button @click="selectChapterHistory(3)">test</el-button> -->
        <span
          style="float: right; line-height: 40px; font-size: 1.3em"
          class="an"
          >更新时间：{{ currentChapter.updateTime }}</span
        >

        <el-dialog
          :visible.sync="lsOpen"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          show-close
          width="850px"
          class="myDialog"
        >
          <!-- width="50%" -->

          <div slot="title">历史版本保留最近五个版本</div>

          <div class="a">
            <div class="b" style="overflow: auto">
              <div
                class="b1"
                v-for="(item, index) in historyList"
                :key="index"
                @click="selectChapterContent(item)"
              >
                <ul>
                  <li>{{ item.split("_")[2] }}</li>
                  <li>{{ item.split("_")[0] }}</li>
                </ul>
              </div>
            </div>

            <div class="c" v-html="chapContent" style="overflow: auto"></div>
            <!-- <div class="d">恢复此版本</div>
            <div class="e">另存为草稿</div> -->
          </div>

          <span slot="footer" class="dialog-footer">
            <!-- <el-button @click="lsOpen = false">取 消</el-button> -->
            <el-button type="primary" @click="hfLs">恢复到当前版本</el-button>
          </span>
        </el-dialog>
      </div>
      <el-alert
        class="warningStyle"
        title="请注意：严禁上传任何情色、低俗、涉政等违法违规内容。一旦查实，视情节严重程度全书屏蔽整改起步并取消福利，直至报警处理。"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
    </div>
    <div class="editrq">
      <el-input
        v-model="currentChapter.title"
        class="title"
        placeholder="标题"
        :disabled="editorOption.readOnly"
      ></el-input>
      <quill-editor
        ref="myLQuillEditor"
        v-model="currentChapter.context"
        :options="editorOption"
        class="editor"
        @blur="onEditorBlur"
        @focus="onEditorFocus"
        @change="onEditorChange"
      >
      </quill-editor>
    </div>
    <!-- 侧边栏 -->
    <el-drawer
      class="ct"
      :visible.sync="drawer"
      direction="ltr"
      :modal="false"
      :show-close="false"
      size="16%"
    >
      <el-menu
        :default-active="startIndex"
        :default-openeds="openIndex"
        @open="clOpen"
        @select="handleSelect"
      >
        <el-submenu index="1">
          <template slot="title">
            <i class="el-icon-location"></i>
            <span>草稿箱</span>
          </template>
          <el-menu-item
            :index="value.updateTime + '_' + value.id"
            v-for="value of draftList"
            :key="value.updateTime + '_' + value.id"
          >
            <el-badge value="存稿" v-if="value.chapterOrder < -1">
              <div style="width: 150px">{{ value.title }}</div>
            </el-badge>
            <div v-else style="width: 150px">{{ value.title }}</div>
          </el-menu-item>
        </el-submenu>
        <el-submenu index="2">
          <template slot="title">
            <i class="el-icon-location"></i>
            <span>已发布</span>
          </template>
          <el-menu-item
            :index="value.updateTime + '_' + value.id"
            v-for="value of publishList"
            :key="value.updateTime + '_' + value.id"
          >
            <el-badge :value="value.chapterOrder">
              <div style="width: 150px">{{ value.title }}</div>
            </el-badge>
          </el-menu-item>
        </el-submenu>
        <el-submenu index="3">
          <template slot="title">
            <i class="el-icon-location"></i>
            <span>回收站</span>
          </template>
          <el-menu-item
            :index="value.updateTime + '_' + value.id"
            v-for="value of deleteList"
            :key="value.updateTime + '_' + value.id"
          >
            <div style="width: 150px">{{ value.title }}</div>
          </el-menu-item>
        </el-submenu>
        <!-- <el-submenu index="4">
          <template slot="title">
            <i class="el-icon-location"></i>
            <span>暂存箱</span>
          </template>
          <el-menu-item index="a"> 第一章 </el-menu-item>
        </el-submenu> -->
      </el-menu>
      <div slot="title">
        <el-input
          placeholder="请输入内容"
          prefix-icon="el-icon-search"
          v-model="input"
          size="small"
        >
        </el-input>
        <div class="addChapter" @click="addChapter">
          <i class="el-icon-plus"></i>
          &nbsp;
          <span>新增章节</span>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
import { dataConfig } from "@/config/mixin.js";
import {
  saveChapter,
  selectDraftList,
  selectChapter,
  getChapterHistory,
  getChapterContent,
  releaseRequest,
  saveAsDraft,
  selectPublishList,
  deleteChapter,
  selectDeleteChapterList,
} from "@/api";

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    quillEditor,
  },

  mixins: [dataConfig],
  data() {
    //这里存放数据
    return {
      lsOpen: false,
      dialogVisible: false,
      //草稿
      draftList: [],
      //已发布
      publishList: [],
      // 侧边栏的搜索框
      input: "",

      release: {
        bookId: this.$route.params.bookId,
        //发布类型：1立刻，2定时
        releaseType: "1",
        //发布周期：1延时，2每天
        releaseCycle: "1",
        //发布时间
        releaseTime: "",
        //发布章节数
        chapterNumber: 1,
      },
      currentChapter: {
        id: "",
        bookId: this.$route.params.bookId,
        chapterOrder: -1,
        paragraphCount: "",
        updateTime: "",
        title: "",
        context: "",
        wordCount: "",
      },
      // 富文本配置
      editorOption: {
        modules: {
          toolbar: [],
        },
        //只读模式
        readOnly: false,
        theme: "snow",
        placeholder: "请输入正文",
        // Some Quill optiosn...
      },
      // 显示侧边栏的标记
      drawer: false,
      //关系到打开的菜单项
      key: "",
      //重新加载后默认打开的菜单
      openIndex: ["1"],
      //历史列表
      historyList: [""],
      //历史记录的文章内容
      chapContent: "",
      //删除提示
      deleteTips: "确定要删除吗？",
      //删除弹出
      deleteDialog: false,
      //删除列表
      deleteList: [],
      //是否选中删除项
      isDeleteItem: false,
      //选中的历史版本项
      xzcg: ",",
    };
  },
  //方法集合
  methods: {
    // theSaveAsDraftTips(){
    //   this.deleteDialog = true;
    //   this.deleteTips = ""
    // },
    hfLs() {
      this.lsOpen = false;
      this.xzcg;
    },
    deleteTipsTc() {
      if (this.currentChapter.chapterOrder > 0) {
        this.$message.info("已发布的章节无法删除");
        return;
      }
      if (this.currentChapter.chapterOrder < -1) {
        this.$message.info("存稿章节无法删除");
        return;
      }
      this.deleteDialog = true;
      if (!this.currentChapter.id) {
        this.deleteTips = "未保存的新建章节将无法恢复,确定要删除吗？";
      } else {
        this.deleteTips = "确定要删除吗？";
      }
    },
    deleteCh() {
      if (this.currentChapter.chapterOrder == -1) {
        deleteChapter(this.currentChapter.id)
          .then(({ data }) => {
            this.$message.success("删除成功");
            for (let i = 0; i < this.draftList.length; i++) {
              if (this.draftList[i].id == this.currentChapter.id) {
                this.deleteList.unshift(this.draftList[i]);
                this.draftList.splice(i, 1);
              }
            }
            if (this.draftList[0]) {
              this.currentChapter = this.draftList[0];
            }
          })
          .catch((err) => {});
        this.deleteDialog = false;
      }
    },
    //将删除记录恢复
    recoverDelete() {},
    // 获取章节的历史版本(获取到的是硬盘中存放的文件名集合) 参数：该章节id
    selectChapterHistory() {
      console.log("历史记录");
      getChapterHistory(this.currentChapter.id)
        .then(({ data }) => {
          console.log("历史记录", data);
          if (data.data.length == 0) {
            this.$message.success("暂无记录");
          } else {
            this.lsOpen = true;
            this.historyList = data.data;
            this.xzcg = data.data[0];
            this.selectChapterContent(data.data[0]);
          }
        })
        .catch((err) => {});
    },
    // 通过章节文件名直接获取章节文件内容
    selectChapterContent(fileName, index) {
      this.xzcg = this.historyList[index];
      // this.chapContent = fileName;
      getChapterContent(fileName)
        .then(({ data }) => {
          console.log("历史内容", data);
          this.chapContent = data.data;
        })
        .catch((err) => {});
    },
    //保存为存稿
    theSaveAsDraft() {
      saveAsDraft(this.currentChapter)
        .then(({ data }) => {
          console.log("保存-------------", data, this);
          let chapter = data.data;
          if (!this.currentChapter.id) {
            this.currentChapter.id = chapter.id;
          }
          this.currentChapter.chapterOrder = chapter.chapterOrder;
          this.currentChapter.updateTime = chapter.updateTime;
          for (let i = 0; i < this.draftList.length; i++) {
            if (this.startIndex == this.draftList[i]) {
              this.draftList.splice(i, 1, this.currentChapter);
              break;
            }
          }
          this.$message.success("存稿成功");
        })
        .catch((err) => {});
    },
    //发布
    sendReleaseRequest() {
      releaseRequest(this.release)
        .then(({ data }) => {
          this.dialogVisible = false;
          if (data.code == 0) {
            if (this.release.releaseType == 1) {
              //TODO:查询发布
              selectPublishList(this.$route.params.bookId)
                .then(({ data }) => {
                  this.publishList = data.data;
                })
                .catch((err) => {});
            }
            this.$message.success("发布成功");
          } else {
            this.$message.error(data.message);
          }
          this.release = {
            bookId: this.$route.params.bookId,
            //发布类型：1立刻，2定时
            releaseType: "1",
            //发布周期：1延时，2每天
            releaseCycle: "1",
            //发布时间
            releaseTime: "",
            //发布章节数
            chapterNumber: 1,
          };
        })
        .catch((err) => {});
    },
    //取消发布
    cancel() {
      this.dialogVisible = false;
      this.release = {
        bookId: this.$route.params.bookId,
        //发布类型：1立刻，2定时
        releaseType: "1",
        //发布周期：1延时，2每天
        releaseCycle: "1",
        //发布时间
        releaseTime: "",
        //发布章节数
        chapterNumber: 1,
      };
    },
    //保存
    saveChapter() {
      //TODO:保存
      saveChapter(this.currentChapter)
        .then(({ data }) => {
          console.log("保存-------------", data, this.currentChapter.id);
          let chapter = data.data;
          if (!this.currentChapter.id) {
            this.currentChapter.id = chapter.id;
          }
          this.currentChapter.updateTime = chapter.updateTime;
          for (let i = 0; i < this.draftList.length; i++) {
            if (this.startIndex == this.draftList[i]) {
              this.draftList.splice(i, 1, this.currentChapter);
              break;
            }
          }
          this.$message.success("保存成功");
        })
        .catch((err) => {});
    },
    //展开菜单项时触发
    clOpen(key, path) {
      console.log("------------------", key, path);
      //展开已发布菜单
      // if ("2" === key && this.publishList.length == 0) {
      if ("2" === key) {
        //查询
        //查询已保存
        this.openIndex = ["2"];
        selectPublishList(this.$route.params.bookId)
          .then(({ data }) => {
            this.publishList = data.data;
          })
          .catch((err) => {});
      }
      if ("3" === key) {
        this.openIndex = ["3"];
        selectDeleteChapterList(this.$route.params.bookId)
          .then(({ data }) => {
            console.log(data);
            this.deleteList = data.data;
          })
          .catch((err) => {});
        //查询
      }
    },
    //选中章节
    handleSelect(key, path) {
      console.log("选中-------------", key, path);
      this.isDeleteItem = false;
      if (path.length == 2) {
        if (path[0] == "1") {
          this.clOne(key);
          this.openIndex = ["1"];
          this.editorOption.readOnly = false;
        } else if (path[0] == "2") {
          this.clTwo(key);
          this.openIndex = ["2"];
          this.editorOption.readOnly = true;
        } else if (path[0] == "3") {
          this.clThree(key);
          this.openIndex = ["3"];
          this.editorOption.readOnly = true;
          this.isDeleteItem = true;
        }
      }
    },
    //选中草稿箱中的内容
    clOne(key) {
      this.key = key;
      let tag;
      let i;
      for (i = 0; i < this.draftList.length; i++) {
        const element = this.draftList[i];
        // console.log(i, element);
        if (element.updateTime + "_" + element.id == key) {
          tag = element;
          break;
        }
      }
      if (tag.id && !tag.context) {
        //不是新建章节,
        //读取文本
        selectChapter(this.$route.params.bookId, tag.id)
          .then(({ data }) => {
            this.currentChapter.context = data.data;
            this.draftList[i].context = data.data;
          })
          .catch((err) => {});
      }
      this.currentChapter = tag;
    },
    //选中已发布内容
    clTwo(key) {
      this.key = key;
      let tag;
      let i;
      for (i = 0; i < this.publishList.length; i++) {
        const element = this.publishList[i];
        if (element.updateTime + "_" + element.id == key) {
          tag = element;
          break;
        }
      }
      if (tag.id && !tag.context) {
        selectChapter(this.$route.params.bookId, tag.id)
          .then(({ data }) => {
            this.currentChapter.context = data.data;
            this.publishList[i].context = data.data;
          })
          .catch((err) => {});
      }
      this.currentChapter = tag;
    },
    //选中已删除内容
    clThree(key) {
      this.key = key;
      let tag;
      let i;
      for (i = 0; i < this.deleteList.length; i++) {
        const element = this.deleteList[i];
        if (element.updateTime + "_" + element.id == key) {
          tag = element;
          break;
        }
      }
      if (tag.id && !tag.context) {
        selectChapter(this.$route.params.bookId, tag.id)
          .then(({ data }) => {
            this.currentChapter.context = data.data;
            this.deleteList[i].context = data.data;
          })
          .catch((err) => {});
      }
      this.currentChapter = tag;
    },
    //添加新章节
    addChapter() {
      let a = {
        id: "",
        bookId: this.$route.params.bookId,
        chapterOrder: -1,
        paragraphCount: "",
        updateTime: this.dateFormat("yyyy-MM-dd HH:mm:ss:SSS", new Date()),
        title: "无章节名",
        context: "",
        wordCount: "",
      };
      this.currentChapter = a;
      this.draftList.unshift(a);
    },
    //选择时间后
    qdTime(value) {
      // var current = this.dateFormat("yyyy-MM-dd HH:mm", value);
      console.log();
      if (value < new Date()) {
        this.release.time = "";
        this.$message.error("不能选择过去时间");
      }
    },
    //前往管理页面
    toWorkBench() {
      console.log("--------toWorkBench------");
      this.$router.push({
        name: "writer",
      });
    },
    //打开
    open() {
      this.drawer = !this.drawer;
    },
    // 失去焦点事件
    onEditorBlur(e) {},
    // 获得焦点事件
    onEditorFocus(e) {
      if (this.editorOption.readOnly) {
        e.enable(false);
      }
    },
    // 内容改变事件
    onEditorChange(e) {},
  },
  //监听属性 类似于data概念
  computed: {
    //
    startIndex() {
      if (!this.key) {
        let start = this.draftList[0];
        // console.log("选中", start);
        if (start) {
          return start.updateTime + "_" + start.id;
        }
      } else {
        return this.key;
      }

      //TODO默认展开项
    },
  },
  //监控data中的数据变化
  watch: {},

  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    selectDraftList(this.$route.params.bookId)
      .then(({ data }) => {
        console.log(data);
        this.draftList = data.data;
        //默认内容
        let ch = this.draftList[0];
        if (ch) {
          this.currentChapter = ch;
          if (ch.id) {
            selectChapter(this.$route.params.bookId, ch.id)
              .then(({ data }) => {
                this.currentChapter.context = data.data;
                this.element[0].context = data.data;
              })
              .catch((err) => {});
          }
        }
      })
      .catch((err) => {});
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
.rq {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background-color: #f5f6f7;
}
.ct {
  top: 73px;
}
.showChapter {
  line-height: 3.5em;
  position: fixed;
  left: 0;
  top: 120px;
  border-top-right-radius: 3em;
  border-bottom-right-radius: 3em;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background-color: white;
}
.showChapter:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
}
.tou {
  /* position: fixed;
  left: 0;
  top: 0; */
  width: 100%;
  padding: 20px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}
.pal {
  margin-left: 40px;
}
.par {
  margin-right: 40px;
}
.editrq {
  position: relative;
  margin: 0 auto;
  width: 60%;
  height: 70%;
  background: white;
}
.editor {
  height: 100%;
}
.title {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  background: white;
}
.title > input {
  width: 100%;
  height: 31px;
}
.addChapter {
  line-height: 2em;
  font-size: 1.6em;
  margin-top: 20px;
}
.toAction {
  margin: 0 auto;
  width: 60%;
  margin-top: 1px;
}
.warningStyle {
  background: #feeceb;
  color: #f2463d;
}
.an {
  color: #7a7a7a;
}
/* start */
.myDialog .el-dialog__body {
  padding: 10px 20px;
  background: red;
}
.el-dialog__body {
  padding: 10px 20px;
  background: red;
}
.a {
  width: 810px;
  height: 380px;
  /* border: 1px solid #000000; */
}
.b {
  width: 230px;
  height: 375px;
  float: left;
  /* padding-top: 25px; */
  border-right: 2px solid #e5e5e6;
}
.b1 {
  width: 229px;
  height: 70px;
  float: left;
}
/* .b1:hover,
.li1 a:hover {
  text-decoration: none;
  background-color: #f5f9ff;
  color: #1070e8;
} */
.li1 {
  margin-top: 10px;
  font-weight: bold;
  margin-left: 20px;
  color: #525252;
}
.li2 {
  margin-top: 5px;
  margin-left: 20px;
  color: #909091;
}
.c {
  width: 500px;
  height: 360px;
  float: left;
  /* margin-top: 35px; */
  margin-left: 40px;
  border-radius: 5px;
  background-color: #f5f5f5;
}
.d {
  width: 120px;
  height: 40px;
  float: right;
  border: 1px solid #ebebec;
  margin-right: 40px;
  margin-top: 20px;
  text-align: center;
  line-height: 40px;
  border-radius: 5px;
  color: #ffffff;
  background-color: #0066e5;
}
.e {
  width: 120px;
  height: 40px;
  border: 1px solid #ebebec;
  float: right;
  margin-right: 20px;
  margin-top: 20px;
  text-align: center;
  line-height: 40px;
  border-radius: 5px;
  color: #505463;
}
/* end */

.ql-toolbar {
  height: 40px;
}
.tcSave {
  margin-left: 10px;
  margin-right: 10px;
}
</style>